<?php

class VolunteerController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{   
    return array(
        array('allow',
            'actions'=>array('admin','create','index','update','delete','view'),
            'roles'=>array('admin'),
        ),
         array('allow',
            'actions'=>array('view','update'),
            'roles'=>array('volunteer','alumni'),
        ),
         array('allow',
            'actions'=>array('create','update','view','index'),
            'roles'=>array('encoder'),
        ),  
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($type)
	{
		$model=new Volunteer;
		$user=new User();
		$user->roles = $type;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Volunteer'], $_POST['User']))
		{
			$model->attributes=$_POST['Volunteer'];
			$user->attributes=$_POST['User'];
			
			//for email 
			$firstname = $user->user_fname;
			$lastname = $user->user_lname;
			$pass = $user->password;

			$uploadedFile = CUploadedFile::getInstance($user,'user_photo');
			$rnd = rand(0123456789, 9876543210); 

			/*$fileName = "{$rnd}-{$uploadedFile}";
			$user->user_photo = $fileName;*/

			/*--password hashing--*/
			if ($user->validate()){

					 $salt = openssl_random_pseudo_bytes(22);
		             $salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
		             $password_hash = crypt($user->password, $salt);
		             $user->password = $password_hash;
			 }

             /*--date format--*/
			$user->user_birthdate = date("Y-m-d",strtotime($user->user_birthdate));

			if($user->save())
			{
				if (!empty($uploadedFile))
				{
           		 $uploadedFile->saveAs(Yii::app()->basePath.'/../files/images/'.$fileName); // save images in given destination folder
      		  	}

		        $model->user_id = $user->id;
		        $model->save();

				//use 'contact' view from views/mail
				$mail = new YiiMailer('contact', array('Firstname' => $firstname,'Lastname' => $lastname,'Password' => $pass, 'Username' => $user->username,));
				
				//set properties
				$mail->setFrom(Yii::app()->params['adminEmail']);
				$mail->setSubject('No Reply');
				$mail->setTo($user->user_email);
				
				//send
				if ($mail->send()) {
					Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				} else {
					Yii::app()->user->setFlash('error','Error while sending email: '.$mail->getError());
				}
				
		        $this->redirect(array('view','id'=>$model->id));
    		}		
		}
			$this->render('create',array(
				'model'=>$model,
				'user'=>$user
	));
}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$user=$this->loadUser($model->user_id);

		if(isset($_POST['Volunteer'], $_POST['User']))
		{
			$model->attributes=$_POST['Volunteer'];
			$user->attributes=$_POST['User'];

			$uploadedFile = CUploadedFile::getInstance($user, 'user_photo');
			$rnd = rand(0123456789, 9876543210);

			$fileName = "{$rnd}-{$uploadedFile}";
                       
        if (!empty($uploadedFile)) $user->user_photo = $fileName;
       
		    $user->user_birthdate = date("Y-m-d",strtotime($user->user_birthdate));
			$model->volunteer_start_date = date("Y-m-d",strtotime($model->volunteer_start_date));
			
		if($user->save()){
			if (!empty($uploadedFile))
				{
           			 $uploadedFile->saveAs(Yii::app()->basePath.'/../files/images/'.$fileName); // save images in given destination folder
      		  	} 	
			$model->user_id = $user->id;
			$model->save();	

			$this->redirect(array('view','id'=>$model->id));
			}		
		}	
		$this->render('update',array(
			'model'=>$model,
			'user'=>$user
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Volunteer');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
  	{
        //$model=new Member('search');
        //$model->unsetAttributes();  
        $criteria=new CDbCriteria();
        $criteria->join = 'JOIN user u on u.id=t.user_id';
        $criteria->condition="u.roles =:b";
        $criteria->params = array(':b'=>'volunteer');  
        
        $model=new CActiveDataProvider('Volunteer',array(
                'pagination' => array(
                     'pageSize' => 30,
                ),'criteria'=>$criteria,
        ));  
        
        if (isset($_GET['keyword']) && $_GET['keyword'] != ""){
	            $keyword = trim($_GET['keyword']);
	            $keyword = str_replace( ' ', '', $keyword);
	            
	            $criteria=new CDbCriteria();
	            $criteria->join = 'JOIN user u on u.id=t.user_id';
	            $criteria->condition="concat_ws('',user_code) LIKE concat('%',:a,'%') OR u.user_fname LIKE concat('%',:a,'%') OR u.user_lname LIKE concat('%',:a,'%')";
	            $criteria->params = array(':a' => $keyword); 
	            
            $model = new CActiveDataProvider('Volunteer',array(
                'pagination' => array(
                     'pageSize' => 30,
                ),
                'criteria'=>$criteria,
            ));  
        }
        
    $this->render('admin',array(
      'model'=>$model,
    ));
  }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Volunteer the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Volunteer::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	public function loadUser($id)
	{
		$user=User::model()->findByPk($id);
		if($user===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $user;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Volunteer $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='volunteer-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
